import React from "react";
import imgUrl from "../../assets/images/placeholder-image.webp";

class LazyLoadImage extends React.Component {
  // 1. 进入可视区  加载
  //    1.1 加载成功 正常展示
  //    1.2 加载失败 显示加载失败
  // 2. 没有进入可视区  展示占位图
  img = React.createRef();
  state = {
    url: imgUrl,
  };
  render() {
    const { height, width } = this.props;
    const { url } = this.state;
    return (
      <img
        ref={this.img}
        src={url}
        alt=""
        style={{ width: width, height: height }}
      />
    );
  }
  componentDidMount() {
    const image = this.img.current;
    const { src } = this.props
    const ob = new IntersectionObserver((entries) => {
      if (entries[0].intersectionRatio <= 0) return;

      this.setState({
        url: src
      });
      ob.unobserve(image)
    });

    ob.observe(image);
  }
}

export default LazyLoadImage;
